<script setup>
import { ref } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const productForm = ref({
  name: '',
  description: '',
  price: '',
  stock: '',
  image: ''
});

function onImageChange(file) {
  productForm.value.image = file.raw;
}

function beforeUpload(file) {
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
  if (!allowedTypes.includes(file.type)) {
    ElMessage.error('只允许上传 JPEG、PNG 和 GIF 格式的图片！');
    return false;
  }
  const maxSize = 5 * 1024 * 1024; // 5MB
  if (file.size > maxSize) {
    ElMessage.error('图片大小不能超过 5MB！');
    return false;
  }
  return true;
}

function publishProduct() {
  axios.post('/api/publishProduct', productForm.value)
      .then(response => {
        if (response.data.success) {
          ElMessage.success('商品发布成功！');
        } else {
          ElMessage.error('商品发布失败！');
        }
      })
      .catch(error => {
        console.error('发布商品时发生错误：', error);
        ElMessage.error('商品发布失败！请检查网络或联系管理员。');
      });
}
</script>

<template>
  <div>
    <div style="width: 500px;margin: 0 auto">
      <h2>发布商品</h2>
      <el-form :model="productForm" label-width="120px">
        <el-form-item label="商品名称">
          <el-input v-model="productForm.name"></el-input>
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input v-model="productForm.description" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="商品价格">
          <el-input v-model="productForm.price"></el-input>
        </el-form-item>
        <el-form-item label="商品库存">
          <el-input v-model="productForm.stock"></el-input>
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload action="#" :on-change="onImageChange" :before-upload="beforeUpload" :show-file-list="false">
            <el-button size="small" color="#EFE154">上传图片</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="publishProduct">发布商品</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped>

</style>